package com.zzxz.practicaltrainingsys.service.impl;

import com.zzxz.practicaltrainingsys.entity.Team;
import com.zzxz.practicaltrainingsys.mapper.TeamMapper;
import com.zzxz.practicaltrainingsys.service.TeamService;
import com.zzxz.practicaltrainingsys.vo.ViewTeam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzxz.practicaltrainingsys.entity.Member;
import com.zzxz.practicaltrainingsys.service.MemberService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zzxz.practicaltrainingsys.component.WebSocketServiceHelper.teamMapper;

@Service
public class TeamServiceImpl implements TeamService {

    @Autowired
    private TeamMapper TeamMapper;

    //在组队信息表（team）里插入组长学号、组名、选题编号、邀请码、项目编号、小组组号。
    @Override
    public int insertTeam(Team team) {
        return TeamMapper.insertTeam(team);
    }

    //插入副组长，根据组号更新team表中的viceleader_id（副组长）字段
    @Override
    public int updateViceleaderId(Team team) {
        return TeamMapper.updateViceleaderId(team);
    }

    //在组队信息表（team）根据组长学号查取邀请码。
    @Override
    public String getInviteCodeByLeaderId(Integer leader_id) {
        return TeamMapper.getInviteCodeByLeaderId(leader_id);
    }

    //根据组号在组队信息表（team）插入小组分数
    @Override
    public int updateGroupMarks(Team team) {
        return TeamMapper.updateGroupMarks(team);
    }

    //根据组号在组队信息表（team）查询小组成绩
    @Override
    public String getGroupMarksByTeamId(Integer team_id) {
        return TeamMapper.getGroupMarksByTeamId(team_id);
    }

    //组队所有信息
    @Override
    public List<ViewTeam> getViewTeamsPage(int offset, int pageSize) {
        return TeamMapper.getViewTeamsPage(offset, pageSize);
    }
    @Override
    public int getTotalCount() {
        return TeamMapper.getTotalCount();
    }

    @Override
    public int countByTopicId(Integer topic_id) {
        return TeamMapper.countByTopicId(topic_id);
    }


    @Override
    public Map<String, Object> createTeamAndJoin(Map<String, Object> params, MemberService memberService) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 参数校验
            if (params == null || params.isEmpty()) {
                result.put("success", false);
                result.put("msg", "参数不能为空");
                return result;
            }

            String inviteCode = (String) params.get("invite_code");
            Integer topicId = (Integer) params.get("topic_id");
            Integer projectId = (Integer) params.get("project_id");
            Integer leaderId = (Integer) params.get("leader_id");
            String teamName = (String) params.get("team_name");

            // 校验必要参数
            if (inviteCode == null || topicId == null || projectId == null || leaderId == null || teamName == null) {
                result.put("success", false);
                result.put("msg", "缺少必要参数");
                return result;
            }

            // 1. 校验邀请码唯一
            if (TeamMapper.countByInviteCode(inviteCode) > 0) {
                result.put("success", false);
                result.put("msg", "邀请码已存在");
                return result;
            }

            // 2. 校验该项目下该选题的小队数量（同步前端逻辑）
            if (TeamMapper.countByProjectAndTopic(projectId, topicId) >= 2) {
                result.put("success", false);
                result.put("msg", "该选题下已存在两个小队");
                return result;
            }

            // 3. 获取当前project下最大group_id并+1
            int maxGroupId = TeamMapper.getMaxGroupIdByProjectId(projectId);
            int newGroupId = maxGroupId + 1;

            // 4. 插入team
            Team team = new Team();
            team.setLeader_id(leaderId);
            team.setTeam_name(teamName);
            team.setTopic_id(topicId);
            team.setInvite_code(inviteCode);
            team.setProject_id(projectId);
            team.setGroup_id(newGroupId);

            int insertTeamResult = TeamMapper.insertTeam(team);
            if (insertTeamResult != 1) {
                result.put("success", false);
                result.put("msg", "创建队伍失败");
                return result;
            }

            // 5. 获取刚插入的team_id
            Integer teamId = TeamMapper.getLastInsertTeamId();
            if (teamId == null) {
                result.put("success", false);
                result.put("msg", "获取队伍ID失败");
                return result;
            }

            // 6. 插入member（组长自动成为成员）
            Member member = new Member();
            member.setTeam_id(teamId);
            member.setStudent_id(leaderId);
            member.setMember_marks(null);

            int insertMemberResult = memberService.insertMember(member);

            if (insertMemberResult == 1) {
                result.put("success", true);
                result.put("msg", "创建成功");
                result.put("teamId", teamId);
            } else {
                result.put("success", false);
                result.put("msg", "成员插入失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "服务器内部错误: " + e.getMessage());
        }

        return result;
    }


    @Override
    public Team findByInviteCode(String invite_code) {
        return teamMapper.findByInviteCode(invite_code);
    }

    //判断角色
    @Override
    public String getUserRole(int studentId) {
        int leaderCount = teamMapper.countAsLeader(studentId);
        if (leaderCount > 0) {
            return "leader";
        }
        int viceLeaderCount = teamMapper.countAsViceLeader(studentId);
        if (viceLeaderCount > 0) {
            return "viceLeader";
        }
        int memberCount = teamMapper.countAsMember(studentId);
        if (memberCount > 0) {
            return "member";
        }
        return "unknown";
    }

    @Override
    public int countByProjectAndTopic(Integer project_id, Integer topic_id) {
        return TeamMapper.countByProjectAndTopic(project_id, topic_id);
    }

    @Override
    public Team getTeamInfo(Integer team_id) {
        return TeamMapper.getTeamInfo(team_id);
    }

    //根据学号和项目id查找邀请码
    @Override
    public ViewTeam getTeamByStudentAndProject(Integer studentId, Integer projectId) {
        if (studentId == null || projectId == null) {
            throw new IllegalArgumentException("学生ID和项目ID不能为空");
        }

        ViewTeam team = teamMapper.getTeamByStudentAndProject(studentId, projectId);
        if (team == null) {
            throw new RuntimeException("未找到该学生在指定项目中的团队信息");
        }

        return team;
    }

    @Override
    public List<Team> getTeamsByTopicId(Integer topic_id) {
        return teamMapper.getTeamsByTopicId(topic_id);
    }

    @Override
    public int updateTeamScore(Integer team_id, Double group_marks) {
        return teamMapper.updateTeamScore(team_id, group_marks);
    }

}
